package com.bsp.autobean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


/**
 * 注册拦截器
 * Created by zyf on 2017/5/12 0012.
 */
@Configuration
public class InterceptorConfiguration extends WebMvcConfigurerAdapter {

    @Value(value = "${interceptor.class.name:false}")
    private String interceptorClassName="";

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        if (!"false".equals(this.interceptorClassName)){
            String[] classNames=this.interceptorClassName.split(",");
            for (int i=0;i<classNames.length;i++){
                try {
                    Class clas=Class.forName(classNames[i]);
                    Object obj = clas.newInstance();
                    if (obj instanceof HandlerInterceptor){
                        HandlerInterceptor handler=(HandlerInterceptor)obj;
                        InterceptorRegistration Registration=registry.addInterceptor(handler);
                        Registration.addPathPatterns("/**");
                    }else{
                        throw new RuntimeException(classNames[i]+" no implements HandlerInterceptor");
                    }
                }catch(Exception e){
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }
}
